package com.coder4j;

import com.coder4j.auth.entity.AuthApiEntity;
import com.coder4j.auth.ApiUtils;
import com.coder4j.auth.service.AuthApiService;
import com.coder4j.cache.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.CodeSource;
import java.util.List;

@Component
@Slf4j
public class AppRunner  implements ApplicationRunner {
    @Value("${spring.application.name}")
    private String appName;

    @Resource
    private AuthApiService authApiService;

    private static String getJarPath() {
        CodeSource codeSource = AppRunner.class.getProtectionDomain().getCodeSource();
        if (codeSource != null) {
            return codeSource.getLocation().getPath();
        }
        return null;
    }


    /**
     * 项目启动时，将API添加到数据库中
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        String rootPath = getJarPath();

        List<AuthApiEntity> apiList = ApiUtils.getApiList(appName,rootPath, Application.class.getPackage().getName());

        log.info("{},{}", apiList.size(), apiList);

        //更新API
        authApiService.batchSave(apiList);

        new Thread(()->{
            try {
                Thread.sleep(60000L);

                ApiCache.initCache();

                ButtonCache.initCache();

                GroupCache.initCache();

                OrganizationCache.initCache();

                RoleCache.initCache();

                RoleCache.initRoleApiCache();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();


    }
}
